<?php

namespace Admin\Model;

use Think\Model;

class CategoryModel extends Model
{
    public function getChildren($catId)
    {
        $data = $this->select();
        return $this->_getChildren($data,$catId,TRUE);
    }

    private function _getChildren($data,$catId,$isClear = FALSE)
    {
        static $_ret = array();
        if($isClear)
            $_ret = array();
        foreach($data as $k => $v)
        {
            if($v['parent_id'] == $catId)
            {
                $_ret[] = $v['id'];
                $this->_getChildren($data,$v['id']);
            }
        }
        return $_ret;
    }

    public function getTree()
    {
        $data = $this->select();

        return $this->_getTree($data);
    }

    private function _getTree($data,$parent_id=0,$level=0)
    {

        static $_ret = array();
        foreach($data as $k => $v)
        {
            if($v['parent_id'] == $parent_id)
            {
                $v['level'] = $level;
                $_ret[] = $v;
                $this->_getTree($data,$v['id'],$level+1);
            }
        }

        return $_ret;

    }

    protected function _before_delete(&$option)
    {
        $children = $this->getChildren($option['where']['id']);
        if($children)
        {
            $children = implode(',',$children);
            $model = new \Think\Model;
            $model->table('__CATEGORY__')->delete($children);
        }
    }

    public function getGoodsIdByCatId($catId)
    {
        $catModel = D('category');
        $children = $catModel->getChildren($catId);
        $children[] = $catId;
        $gids = $this->field('id')->where(array(
            'cat_id' => array('in',$children),
        ))->select();
        $gcModel = D('goods_cat');
        $gids1 = $gcModel->field('DISTINCT goods_id id')->where(array(
           'cat_id' => array('in',$children)
        ))->select();
        if($gids && $gids1)
            $gids = array_merge($gids,$gids1);
        elseif($gids1)
            $gids = $gids1;
        $id = array();
        foreach ($gids as $k => $v)
        {
            if(!in_array($v['id'],$id))
                $id[] = $v['id'];
        }
        return $id;
    }
}